package com.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.entity.SysRole;
import com.rbac.mapper.SysRoleMapper;
import com.rbac.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 角色服务实现类
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@Service
@Transactional
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Override
    public IPage<SysRole> page(IPage<SysRole> page, String roleName, String roleCode, Integer status) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(roleName), SysRole::getRoleName, roleName)
               .like(StringUtils.hasText(roleCode), SysRole::getRoleCode, roleCode)
               .eq(status != null, SysRole::getStatus, status)
               .orderByAsc(SysRole::getSortOrder)
               .orderByDesc(SysRole::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    public List<Long> getPermissionIdsByRoleId(Long roleId) {
        return baseMapper.selectPermissionIdsByRoleId(roleId);
    }

    @Override
    public List<Long> getMenuIdsByRoleId(Long roleId) {
        return baseMapper.selectMenuIdsByRoleId(roleId);
    }

    @Override
    public boolean assignPermissionsToRole(Long roleId, List<Long> permissionIds) {
        // 先删除角色现有权限
        baseMapper.deleteRolePermissionsByRoleId(roleId);
        
        // 添加新权限
        if (permissionIds != null && !permissionIds.isEmpty()) {
            return baseMapper.insertRolePermissions(roleId, permissionIds) > 0;
        }
        return true;
    }

    @Override
    public boolean assignMenusToRole(Long roleId, List<Long> menuIds) {
        // 先删除角色现有菜单
        baseMapper.deleteRoleMenusByRoleId(roleId);
        
        // 添加新菜单
        if (menuIds != null && !menuIds.isEmpty()) {
            return baseMapper.insertRoleMenus(roleId, menuIds) > 0;
        }
        return true;
    }

    @Override
    public boolean existsByRoleCode(String roleCode) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleCode, roleCode);
        return count(wrapper) > 0;
    }

    @Override
    public boolean existsByRoleCodeAndIdNot(String roleCode, Long id) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleCode, roleCode)
               .ne(SysRole::getId, id);
        return count(wrapper) > 0;
    }
}
